package com.study.framework.util;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.springframework.web.servlet.view.document.AbstractExcelView;



public class ExcelView extends AbstractExcelView {
	static SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd_HHmm");	
	
	@SuppressWarnings({ "unchecked", "rawtypes"})
	@Override
	protected void buildExcelDocument(Map<String, Object> model, HSSFWorkbook workbook, HttpServletRequest request, HttpServletResponse response) throws Exception {
		Object temp = model.get("lists");
		
		if(temp == null){
			List<Map<String, String>> list = (List<Map<String, String>>) model.get("list");
			List<String> title = (List<String>) model.get("title");

			//log.debug("{}", list.toString());
			
			buildExcelSheet(workbook, list, title);
		}else{
			List<List<Map<String, String>>> lists = (List<List<Map<String, String>>>) temp;
			List<List<String>> titles = (List<List<String>>) model.get("titles");
			//log.debug("{}", lists.toString());
			
			int i = 0;
			for(List<Map<String, String>> list: lists){
				buildExcelSheet(workbook, list, titles.get(i));
				
				i++;
			}
		}
		
		Date now = new Date();
		
		String uri = request.getRequestURI().replace("/excel.xls", "");
		StringBuilder filename = new StringBuilder();
		
		filename.append(model.get("fileName")).append(".xls");
		
		// filename attach 형태로 변환 앞쪽에 붙임
		filename.insert(0, "attachment; filename=\"");
		filename.append("\"");
		
		
		
		response.setContentType("Application/Msexcel");
		response.setHeader("Content-Disposition", filename.toString());
	}
	
	
	private void buildExcelSheet(HSSFWorkbook workbook, List<Map<String, String>> list, List<String> title) {
		HSSFSheet sheet = workbook.createSheet();

		Cell cell = null;

		CellStyle cs = workbook.createCellStyle();
		cs.setDataFormat(HSSFDataFormat.getBuiltinFormat("text"));

		int rowNum = 0;
		
		HSSFRow row = sheet.createRow(rowNum++);
		writeTitle(row, cell, cs, title);
		
		
		if(list == null){
			HSSFRow r = sheet.createRow(rowNum++);
			cell = r.createCell(0);
	        cell.setCellStyle(cs);
	        cell.setCellValue("데이터가 없습니다");
		}else{
			for (Map<String, String> mapRow : list) {
				HSSFRow r = sheet.createRow(rowNum++);

				int i = 0;
				for(String t: title) {
					cell = r.createCell(i);
			        cell.setCellStyle(cs);
			        cell.setCellValue(String.valueOf(mapRow.get(t)));
			        
			        // null 스트링일 경우 공백으로 처리해버림
			        if(cell.getStringCellValue().equals("null"))
			        	cell.setCellValue("");
			        
			        i++;

				}
			}	
		}
	}

	// 제목 세팅
	private void writeTitle(Row row, Cell cell, CellStyle cs, List<String> title) {
		int i = 0;
		for(String t: title) {
			cell = row.createCell(i);
            cell.setCellStyle(cs);
            cell.setCellValue(t);
            i++;
		}
	}
}
